package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.BrandDTO;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 虎哥
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {


    @Autowired
    private CategoryBrandService categoryBrandService;


    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows) {

        //分页
        Page<Brand> p = new Page<>(page, rows);
        //判断分页条件是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        //如果存在查询条件,则根据条件查询
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key).page(p);
        //查询的结果封装
        List<Brand> brandList = p.getRecords();

        return new PageDTO(p.getTotal(), p.getPages(), BrandDTO.convertEntityList(brandList));
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long categoryId) {
        /*//1.根据分类id查询categoryBrand的集合
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("category_id", id).list();
        //2.获取集合中品牌id的集合
        List<Long> ids = categoryBrandList.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());
        //3.根据品牌ids集合查询品牌信息
        List<Brand> brandList = listByIds(ids);

        return BrandDTO.convertEntityList(brandList);*/
        // 根据分类查询
        List<Brand> list =  getBaseMapper().queryByCategoryId(categoryId);
        // 转换DTO并返回
        return BrandDTO.convertEntityList(list);
    }

    @Override
    public void saveBrand(BrandDTO brandDTO) {
        //1.保存brand信息到数据库
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        //2.保存brandid和categoryid 到中间表 tb_category_brand
        //2.1 获取brandid
        Long brandId = brand.getId();
        //2.2 获取中间表id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //2.3 把id封装到categoryBrand对象中
        ArrayList<CategoryBrand> categoryBrands = new ArrayList<>();
        //2.3.1遍历categoryIds,得到每一个id
        for (Long categoryId : categoryIds) {
            //2.3.4把 id封装到CategoryBrand中
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            // 把id封装到CategoryBrand中数据添加到集合中
            categoryBrands.add(categoryBrand);
        }
        //2.4批处理数据
        categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    public void updateBrand(BrandDTO brandDTO) {
        //1.更新数据库(用前端传来的数据取代数据库中的内容)
        boolean flag = updateById(brandDTO.toEntity(Brand.class));
        //2.判断是否成功
        if (flag == false) {
            throw new LyException(500, "数据更新失败!!!");
        }
        //3.删除中间表信息
        boolean flag2 = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_Id", brandDTO.getId()));
        //4.判断是否删除成功
        if (flag2 == false) {
            throw new LyException(500, "更新品牌失败!!!删除中间表失败!!!");
        }
        //5.把更新后的内容插入到中间表
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //把id封装到categoryBrand对象中
        ArrayList<CategoryBrand> categoryBrands = new ArrayList<>();
        //遍历categoryIds,得到每一个id
        for (Long categoryId : categoryIds) {
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandDTO.getId());
            categoryBrands.add(categoryBrand);
        }
        //2.4批处理数据
        categoryBrandService.saveBatch(categoryBrands);
    }


}